<template>
  <view class="account-info-page">
    <Navbar
      title="账号信息"
    />

    <view class="info-list">
      <view class="info-item" @click="editAvatar">
        <text class="info-label">头像</text>
        <view class="info-right">
          <image class="avatar" :src="userInfo.avatar" mode="aspectFill" />
          <image
            class="info-arrow"
            src="/static/img/minePages/mine-arrow.png"
            mode="widthFix"
          />
        </view>
      </view>
      <view class="divider"></view>
      <view class="info-item">
        <text class="info-label">姓名</text>
        <view class="info-right">
          <text class="info-value">{{ userInfo.nickname }}</text>
          <image
            class="info-arrow"
            src="/static/img/minePages/mine-arrow.png"
            mode="widthFix"
          />
        </view>
      </view>
      <view class="divider"></view>
      <view class="info-item">
        <text class="info-label">所属单位</text>
        <view class="info-right">
          <text class="info-value">{{ userInfo.department }}</text>
          <image
            class="info-arrow"
            src="/static/img/minePages/mine-arrow.png"
            mode="widthFix"
          />
        </view>
      </view>
      <view class="divider"></view>
      <view class="info-item" @click="showPasswordPopup">
        <text class="info-label">密码</text>
        <view class="info-right">
          <text class="info-value">******</text>
          <image
            class="info-arrow"
            src="/static/img/minePages/mine-arrow.png"
            mode="widthFix"
          />
        </view>
      </view>
    </view>

    <!-- 头像弹窗，和consoleView用法一致 -->
    <tn-popup
      v-model="showPopup"
      open-direction="bottom"
      height="300rpx"
      bg-color="#172869"
      radius="30"
      overlay
      safe-area-inset-bottom
    >
      <view class="popup-option" @click="chooseFromAlbum">从相册选择</view>
      <view class="popup-divider"></view>
      <view class="popup-option" @click="takePhoto">拍照上传</view>
      <view class="popup-divider"></view>
      <view class="popup-option cancel" @click="showPopup = false">取消</view>
    </tn-popup>


    <!-- 密码修改弹窗 -->
    <tn-popup 
      v-model="showPasswordDialog" 
      open-direction="center"
      width="600"
      bg-color="#172869"
      radius="20"
    >
      <view class="password-popup">
        <view class="popup-header">
          <text class="popup-title">修改密码</text>
          <text class="password-tips">密码长度8-20位，必须包含数字和字母</text>
        </view>
        <view class="popup-content">
          <!-- 第一步：输入原密码 -->
          <view v-if="passwordStep === 1" class="input-group">
            <text class="input-label">原密码</text>
            <input 
              class="password-input"
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              maxlength="20"
              @input="onPasswordInput"
            />
          </view>
          
          <!-- 第二步：输入新密码 -->
          <view v-if="passwordStep === 2" class="input-group">
            <text class="input-label">新密码</text>
            <input 
              class="password-input"
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              maxlength="20"
              @input="onPasswordInput"
            />
          </view>
          
          <!-- 第三步：确认新密码 -->
          <view v-if="passwordStep === 3" class="input-group">
            <text class="input-label">确认新密码</text>
            <input 
              class="password-input"
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              maxlength="20"
              @input="onPasswordInput"
            />
          </view>
          
          <!-- 错误提示 -->
          <view class="error-tip" v-if="passwordError">
            <text class="error-text">{{ passwordError }}</text>
          </view>
        </view>
        
        <view class="popup-footer">
          <view class="popup-btn confirm-btn" @click="confirmPasswordChange">
            {{ passwordStep === 3 ? '确认修改' : '下一步' }}
          </view>
        </view>
      </view>
    </tn-popup>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { useGlobalStore } from '@/store/app';
import { storeToRefs } from 'pinia';
import { createRequest } from '@/utils/request';
import Navbar from '@/components/Navbar.vue';
import { mygo } from '@/utils/useNavigator';
import { validatePassword } from '@/utils/validators';

// 获取用户信息存储
const globalStore = useGlobalStore();
const { userInfo } = storeToRefs(globalStore);

const showPopup = ref(false);
const isUploading = ref(false);

// 密码修改相关状态
const showPasswordDialog = ref(false);
const passwordStep = ref(1); // 1: 原密码, 2: 新密码, 3: 确认密码
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const passwordError = ref('');

function editAvatar() {
  showPopup.value = true;
}

// 显示密码修改弹窗
function showPasswordPopup() {
  showPasswordDialog.value = true;
  passwordStep.value = 1;
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  };
  passwordError.value = '';
}

// 监听密码输入框变化
function onPasswordInput() {
  // 当输入框为空时，隐藏错误提示
  const currentField = passwordStep.value === 1 ? passwordForm.value.oldPassword :
                      passwordStep.value === 2 ? passwordForm.value.newPassword :
                      passwordForm.value.confirmPassword;
  
  if (!currentField.trim()) {
    passwordError.value = '';
  }
}



// 确认密码修改
async function confirmPasswordChange() {
  const currentStep = passwordStep.value;
  
  if (currentStep === 1) {
    // 验证原密码
    const oldPassword = passwordForm.value.oldPassword.trim();
    if (!oldPassword) {
      passwordError.value = '请输入原密码';
      return;
    }
    
    try {
      // 调用后端接口验证原密码
      const response = await createRequest('/test/password', {
        data: oldPassword
      });
      // 假设返回结果是布尔类型
      if (response.data) {
        // 原密码正确，进入下一步
        passwordStep.value = 2;
        passwordError.value = '';
      } else {
        passwordError.value = '原密码错误';
      }
    } catch (error) {
      passwordError.value = '验证原密码失败，请重试';
    }
  } else if (currentStep === 2) {
    // 验证新密码
    const newPassword = passwordForm.value.newPassword.trim();
    if (!newPassword) {
      passwordError.value = '请输入新密码';
      return;
    }
    
    // 使用已封装的密码验证函数
    const validationResult = validatePassword(newPassword, '密码', 8, 20);
    if (!validationResult.isValid) {
      passwordError.value = validationResult.message || '密码验证失败';
      return;
    }
    
    // 新密码不能与原密码相同
    if (newPassword === passwordForm.value.oldPassword) {
      passwordError.value = '新密码不能与原密码相同';
      return;
    }
    
    // 进入确认密码步骤
    passwordStep.value = 3;
    passwordError.value = '';
  } else if (currentStep === 3) {
    // 确认新密码
    const newPassword = passwordForm.value.newPassword.trim();
    const confirmPassword = passwordForm.value.confirmPassword.trim();
    
    if (!confirmPassword) {
      passwordError.value = '请确认新密码';
      return;
    }
    
    if (newPassword !== confirmPassword) {
      passwordError.value = '两次输入的密码不一致';
      return;
    }
    
    // 提交密码修改
    try {
      const updateData = {
        userId: userInfo.value.userId,
        password: newPassword
      };
      
      const response = await createRequest('/user/edit', {
        data: updateData,
      });

      if (response && response.code === 200) {
        uni.showToast({ 
          title: '密码修改成功', 
          icon: 'success' 
        });
        globalStore.clearUserInfo();
        showPasswordDialog.value = false;
        uni.reLaunch({
          url: '/pages/login'
        });

      } else {
        throw new Error(response?.msg || '密码修改失败');
      }
    } catch (error) {
      console.error('密码修改失败:', error);
      passwordError.value = error.message || '密码修改失败，请重试';
    }
  }
}

// 从相册选择图片
async function chooseFromAlbum() {
  showPopup.value = false;

  if (isUploading.value) {
    return;
  }

  try {
    // 选择图片
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
    });

    const tempFilePath = res.tempFilePaths[0];
    // 上传图片
    await uploadAvatar(tempFilePath);
  } catch (error) {
    console.error('选择图片失败:', error);
  }
}

// 拍照上传
async function takePhoto() {
  showPopup.value = false;

  if (isUploading.value) {
    return;
  }

  try {
    // 拍照
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
    });

    const tempFilePath = res.tempFilePaths[0];
    // 上传图片
    await uploadAvatar(tempFilePath);
  } catch (error) {
    console.error('拍照失败:', error);
  }
}

// 上传头像
async function uploadAvatar(filePath) {
  isUploading.value = true;

  try {
    uni.showLoading({ title: '上传中...', mask: true });

    // 第一步：上传文件到服务器
    const uploadRes = await uni.uploadFile({
      url: 'http://192.168.1.4:8089/api/staticFile/upload',
      filePath: filePath,
      name: 'file',
      header: {
        Authorization: userInfo?.token || '',
      },
      formData: {
        type: '3',
      },
    });

    const uploadResult = JSON.parse(uploadRes.data);
    if (uploadResult.code !== 200) {
      throw new Error(uploadResult.msg);
    }
    // 第二步：更新用户头像
    try {
      const updateRes = await createRequest('/user/update/avatar', {
        method: 'POST',
        data: {
          avatarUrl: uploadResult.data.fileUrl,
        }
      });

      if (updateRes.code === 200 || updateRes.code === 0) {
        // 更新本地用户信息
        globalStore.setUserInfo({
          avatar: uploadResult.data.fileUrl,
        });

        uni.showToast({
          title: '头像更新成功',
        });
      } else {
        throw new Error(updateRes.msg);
      }
    } catch (updateError) {
      console.log('头像更新错误详情:', {
        error: updateError,
        message: updateError.message,
        stack: updateError.stack,
        uploadResult: uploadResult,
        fileUrl: uploadResult.data.fileUrl
      });
      throw new Error(`头像更新失败: ${updateError.message}`);
    }
  } catch (error) {
    uni.showToast({
      title: error.message,
    });
  } finally {
    isUploading.value = false;
    uni.hideLoading();
  }
}
</script>

<style scoped lang="scss">
.account-info-page {
  @include page-with-header;
  background: #172869;
  min-height: 100vh;
}
.info-list {
  margin-top: 40rpx;
}
.info-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  height: 100rpx;
  color: rgba(255, 255, 255, 0.8);
  font-size: 30rpx;
  background: transparent;
  justify-content: space-between;
}
.info-label {
  font-size: 30rpx;
}
.info-right {
  display: flex;
  align-items: center;
}
.avatar {
  width: 108rpx;
  height: 108rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}
.info-value {
  color: #b0b8d0;
  font-size: 28rpx;
  margin-right: 16rpx;
}
.info-arrow {
  width: 14rpx;
}
.divider {
  height: 2rpx;
  background: #1a2e5a;
  margin: 0 40rpx;
}
.popup-option {
  color: #fff;
  text-align: center;
  font-size: 32rpx;
  height: 96rpx;
  line-height: 96rpx;
}
.popup-divider {
  height: 1rpx;
  background: linear-gradient(
    90deg,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0.3) 50%,
    rgba(255, 255, 255, 0.1) 100%
  );
}

/* 密码修改弹窗样式 */
.password-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 40rpx;
  box-sizing: border-box;
}

.popup-header {
  text-align: center;
  margin-bottom: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.popup-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.password-tips {
  color: rgba(255, 255, 255, 0.6);
  font-size: 24rpx;
}

.popup-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  margin-bottom: 40rpx;
}

.input-group {
  display: flex;
  flex-direction: column;
}

.input-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.password-input {
  color: #fff;
  font-size: 30rpx;
  background: rgba(255, 255, 255, 0.08);
  border: 1rpx solid rgba(255, 255, 255, 0.15);
  border-radius: 12rpx;
  padding: 28rpx 24rpx;
  height: 88rpx;
  box-sizing: border-box;
  transition: all 0.3s ease;
  outline: none;
}

.password-input:focus {
  border-color: #268DD9;
  background: rgba(255, 255, 255, 0.12);
  box-shadow: 0 0 0 2rpx rgba(38, 141, 217, 0.2);
}

.password-input::placeholder {
  color: rgba(255, 255, 255, 0.4);
}

.error-tip {
  margin-top: 10rpx;
  padding: 10rpx 20rpx;
  background-color: rgba(255, 71, 87, 0.1);
  border: 1rpx solid rgba(255, 71, 87, 0.2);
  border-radius: 8rpx;
  display: flex;
  align-items: center;
}

.error-text {
  color: #ff4757;
  font-size: 24rpx;
}

.popup-footer {
  display: flex;
  justify-content: center;
  padding-top: 20rpx;
  border-top: 1rpx solid rgba(255, 255, 255, 0.1);
}

.popup-btn {
  width: 100%;
  height: 88rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.popup-btn:active {
  transform: scale(0.98);
}

.popup-btn.confirm-btn {
  background: linear-gradient(135deg, #279BD5 0%, #2264EB 100%);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(30, 200, 225, 0.3);
}
</style>
